<?php

class UploadController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model = new UploadForm();
		
		if(isset($_POST['UploadForm']))
		{
			$model->attributes=$_POST['UploadForm'];
            $model->item = CUploadedFile::getInstance($model,'item');
            
		 	if($model->validate())
            {
            	$upload_file_id = uniqid();
                $model->item->saveAs('upload/' . $upload_file_id . '.xml');
                
                $file_content = file_get_contents('upload/' . $upload_file_id . '.xml');
                
                preg_match_all("#\s*<body>(.*?)</body>#si", $file_content, $body_matches);
                preg_match_all("#\s*<header>(.*?)</header>#si", $file_content, $header_matches);
                preg_match_all("#\s*<footer>(.*?)</footer>#si", $file_content, $footer_matches);
                
                $history = new History();
            	$history->uuid      = $upload_file_id;
				$history->user      = Yii::app()->user->getId() ? Yii::app()->user->getId() : 'NULL';
				$history->shared    = Yii::app()->user->getId() ? '0' : '1';
				$history->ip        = $_SERVER['REMOTE_ADDR'];
				$history->header    = $header_matches[1][0];
				$history->footer    = $footer_matches[1][0];
				$history->body      = $body_matches[1][0];
				$history->timestamp = time();
				
				if ($history->validate()) {
					$history->save();
				}
				
				$this->redirect(array('/site/index','id'=>$upload_file_id));
            }
            
		}
		
		$this->render('index',array(
			'model' => $model,
		));
	}
}
